const Koa = require('koa');
const bodyParser = require('koa-bodyparser');
const controller = require('./controller');
const app = new Koa();
require('./ws');
const staticServer = require('koa-static');
app.use(staticServer(__dirname , 'public'));
const seq = require('./utils/db');
// const User = require('./model/user');


try {
	seq.authenticate();
	console.log('Connection has been established successfully.');
} catch (error) {
	console.error('Unable to connect to the database:', error);
}

// 获取ip地址并在控制台打印
const os = require('os');
const port = 3000;
// 引入控制台打印颜色
require('console-color-mr');
//获取本机ipv4地址
function getIPv4() {
	//同一接口可能有不止一个IP4v地址，所以用数组存
	let ipv4s = [];
	//获取网络接口列表对象
	let interfaces = os.networkInterfaces();
	Object.keys(interfaces).forEach(function (key) {
		interfaces[key].forEach(function (item) {
			//跳过IPv6 和 '127.0.0.1'
			if ('IPv4' !== item.family || item.internal !== false) return;
			ipv4s.push(item.address); //可用的ipv4s加入数组
			// console.log(key + '--' + item.address);
		})
	})
	return ipv4s[0]; //返回一个可用的即可
}
let ipv4 = getIPv4();
// 发json方法 send
function render(json) {
	this.set("Content-Type", "application/json")
	this.body = JSON.stringify(json)
}
app.use(async (ctx, next) => {
	// log request URL: //
	console.log(`Process ${ctx.request.method} ${ctx.request.url}`);
	// 写一个发json方法 send
	ctx.send = render.bind(ctx)
	await next();
});

// parse request body:
app.use(bodyParser());
app.use(controller());

// 端口号
app.listen(port, () => {
	console.log('Listening at ' + 'http://localhost:'.green + port.green + '/public/test.html\n'.green + 'or at ' + 'http://'.green +
		ipv4.green + ':'.green + port.green)
});